<script setup lang="ts">
import { ROOT_NODE_KEY } from "@/constants/symbols";
import { onMounted, onBeforeUnmount } from "vue";
import { createNode } from "@/utils/calculate.ts";
import { draw } from "@/canvas/dom";
import { nodeRegistry } from "@/utils/layoutNodeRegistry.ts";
import { eventBus } from '@/utils/eventBus.ts'
import { Application, Assets, Sprite } from 'pixi.js';
const ROOT_NODE_KEY = "ROOT_NODE_KEY";
const pixi = new Application();
const pixiCanvas = pixi.canvas
onMounted(()=>{
  document.body.appendChild(pixiCanvas);
})
const props = withDefaults(
  defineProps<{
    width?: number;
    height?: number;
  }>(),
  {
    width: 100,
    height: 100
  }
);

let rootNode = null;
function generateLayoutTree(node: any, parentOffset = { x: 0, y: 0 }) {
  const layout = node.getComputedLayout();

  // 计算当前节点的绝对位置（累加父节点的偏移量）
  const absolutePosition = {
    left: parentOffset.x + layout.left,
    top: parentOffset.y + layout.top,
    width: layout.width,
    height: layout.height
  };

  const nodeData = {
    layout: absolutePosition,
    children: []
  };

  // 递归处理子节点，传递累积的偏移量
  const childCount = node.getChildCount();
  if (childCount > 0) {
    for (let i = 0; i < childCount; i++) {
      const childNode = node.getChild(i);
      nodeData.children.push(
        generateLayoutTree(childNode, {
          x: absolutePosition.left,
          y: absolutePosition.top
        })
      );
    }
  }
  return nodeData;
}
// 创建根节点
rootNode = createNode({
  id: ROOT_NODE_KEY,
  width: props.width,
  height: props.height
});
nodeRegistry.add(ROOT_NODE_KEY);

const drawCanvas = () => {
  if (rootNode?.node) {
    rootNode.node.calculateLayout();
    const layoutTree = generateLayoutTree(rootNode.node);
    draw(layoutTree);
  }
};
// 节点数量变化的时候重绘
nodeRegistry.setListenerCallback(() => {
  drawCanvas();
});
// 属性变化的时候重排
eventBus.on('trigger-draw', drawCanvas)
onBeforeUnmount(() => {
  nodeRegistry.remove(ROOT_NODE_KEY);
});
defineExpose({
  getNode: () => {
    return rootNode.node;
  },
  drawCanvas,
  pixi,
});
</script>

<template>
  <slot />
</template>
